<?php
namespace core\model;
// +----------------------------------------------------------------------
// | 模型层
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2017 Even Yin All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: Even yin <416467069@qq.com> <13022156261>
// +----------------------------------------------------------------------
use think\Model;
use think\Db;
use think\Validate;
class BaseModel extends Model
{
  protected $table;
  protected $table_name;
  protected $scene_rule = [];
  protected $rule = [];
  protected $msg =  [];
  protected $scene =  [];
  protected $Validate;
  protected $error = '';
  /* ------------------------------------------------------------------ */
  /*
  * 构造函数
  */
  public function __construct($data = []){
      $this->table_name = $this->table;
      $this->table = config('database.prefix').$this->table;
      parent::__construct($data);
  }
  /* -----------------------------------END------------------------------- */
  /*
  * 获取表名
  */
  public function getTableName(){
      return $this->table_name;
  }
  /* ------------------------------------------------------------------ */
  /*
  * 获取空模型数据
  */
  public function getEmptyModel($table){
      $res = Db::query('show columns FROM `' . config('database.prefix') . $table . "`");
      $model = [];
      if ($res) {
          foreach ($res as $key => $v) {
              $model[$v['Field']] = $v['Default'];
              if ($v['Key'] == 'PRI')
                  $model[$v['Field']] = 0;
          }
      }
      return $model;
  }
  /* ------------------------------------------------------------------ */
  /*
  * 数据验证，先进行数据库表字段验证，去除多余字段。
  */
  public function validateData($data=[],$scene='',$batch = NULL){
      $rules = [];
      if(!empty($scene) && isset($this->scene[$scene])){
          $rules = [];
          $scene_rule = $this->scene[$scene];
          foreach ($scene_rule as $k => $v) {
              if(isset($this->scene_rule[$v])){
                  $rules[$v] = $this->scene_rule[$v];
              }
          }
      }
      $this->Validate = new Validate($rules,$this->msg);
      if(!$this->Validate->check($data)){
          $this->error = $this->Validate->getError();
          return false;
      }
      return true;
  }
  /* ------------------------------------------------------------------ */
  /*
  * 保存数据
  */
  public function save($data = [], $where = [], $scene='', $sequence = null){

      $model = $this->getEmptyModel($this->table_name);
      $model_key = [];
      foreach ($model as $key => $value) {
        $model_key[] = $key;
      }

      foreach ($data as $k => $v) {
          if(!in_array($k,$model_key)){
              unset($data[$k]);
          }
      }
      $data_key = [];
      foreach ($data as $k => $v){
        $data_key[] = $k;
      }

      if(empty($where)){
          foreach ($model as $k => $v) {
              if($k!='id' && !in_array($k,$data_key)){
                  $data[$k] = $v;
              }
          }
      }

      // 对数据表字段进行验证
      if(!empty($scene)){
        if($this->validateData($data,$scene) === false) return 0;
      }

      // 保存数据
      $res = parent::save($data, $where, $sequence);
      if(!empty($where))
      {
          //表示更新数据
          if($res == 0)
          {
              if($res !== false)
              {
                  $res = 1;
              }
          }
      }
      return $res;
  }
  /* ------------------------------------------------------------------ */
  /*
  * 修改单个字段值
  */
  public function modifyTableField($pk_name, $pk_id, $field_name, $field_value){
      $res = $this->save([$field_name=>$field_value],[$pk_name => $pk_id]);
      return $res;
  }
  /* ------------------------------------------------------------------ */
  /*
  * 获取一定条件下的数据分页列表
  */
  public function pageQuery($page_index, $page_size, $condition, $order, $field){
      $count = $this->where($condition)->count();
      if ($page_size == 0) {
          $list = $this->field($field)
              ->where($condition)
              ->order($order)
              ->select();
          $page_count = 1;
      } else {
          $start_row = $page_size * ($page_index - 1);
          $list = $this->field($field)
              ->where($condition)
              ->order($order)
              ->limit($start_row . "," . $page_size)
              ->select();
          if ($count % $page_size == 0) {
              $page_count = $count / $page_size;
          } else {
              $page_count = (int) ($count / $page_size) + 1;
          }
      }
      return array(
          'data' => $list,
          'total_count' => $count,
          'page_count' => $page_count
      );
  }
  /* ------------------------------------------------------------------ */
  /*
  * 获取一定条件下的全部数据
  */
  public function getQueryData($condition,$order,$field){
      $list = $this->field($field)->where($condition)->order($order)->select();
      return $list;
  }
  /* ------------------------------------------------------------------ */
  /*
  * 获取一定条件下的数据
  */
  public function getInfo($condition = '', $field = '*'){
      $info = Db::table($this->table)->where($condition)->field($field)->find();
      return $info;
  }
  /* ------------------------------------------------------------------ */
  /*
  * 获取数据表总数据量
  */
  public function getCount($condition){
      $count = Db::table($this->table)->where($condition)->count();
      return $count;
  }
  /* ------------------------------------------------------------------ */
  /*
  * 获取数据表字段总和
  */
  public function getSum($condition, $field){
      $sum = Db::table($this->table)->where($condition)->sum($field);
      if(!empty($sum)) return $sum;
      return 0;
  }
  /* ------------------------------------------------------------------ */
  /*
  * 获取数据表字段最大值
  */
  public function getMax($condition, $field){
      $max = Db::table($this->table)->where($condition)->max($field);
      if(!empty($max)) return $max;
      return 0;
  }
  /* ------------------------------------------------------------------ */
  /*
  * 获取数据表字段最小值
  */
  public function getMin($condition, $field){
      $min = Db::table($this->table)->where($condition)->min($field);
      if(!empty($min)) return $min;
      return 0;
  }
  /* ------------------------------------------------------------------ */
  /*
  * 获取数据表字段均值
  */
  public function getAvg($condition, $field){
      $avg = Db::table($this->table)->where($condition)->avg($field);
      if(!empty($avg)) return $avg;
      return 0;
  }
  /* ------------------------------------------------------------------ */
  /*
  * 获取错误信息
  */
  public function getError(){
    return $this->error;
  }
  /* ------------------------------------------------------------------ */
}
